//
//  Utils.m
//  Molian
//
//  Created by wan song on 2/12/14.
//  Copyright (c) 2014 memeda. All rights reserved.
//

#import "Utils.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>
#import "LoginViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "Reachability.h"


static SystemSoundID shake_sound_male_id = 0;

@implementation Utils

//保存用户资料完整度
+(void)saveUserDataIntegrityNumber:(NSInteger)number
{
    NSString *plistName = [NSString stringWithFormat:@"%@UserDataIntegrity",[MLUser currentUser].objectId];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(number),@"number", nil];
    
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
    
}
//获取用户资料完整度
+(NSInteger)getUserDataIntegrityNumber
{
    NSString *plistName = [NSString stringWithFormat:@"%@UserDataIntegrity",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    if(dic){
        
    }else{
        return 0;
    }
    NSNumber *n = [dic objectForKey:@"number"];
    if (n) {
         return [n integerValue];
    }else{
         return 0;
    }
}


//保存当前口袋恋人的恋人数量
+(void)savePocketloveNumber:(NSInteger)number
{
    number = 2*number+37934;
    NSString *plistName = [NSString stringWithFormat:@"AllPocketloveCount"];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(number),@"number", nil];
    
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
    
}
//获取当前口袋恋人的恋人数量
+(NSInteger)getPocketloveNumber
{
    NSString *plistName = [NSString stringWithFormat:@"AllPocketloveCount"];
    NSDictionary *dic = [Utils plistName:plistName];
    if(dic){
        
    }else{
        return 37934;
    }
    NSNumber *n = [dic objectForKey:@"number"];
    if (n) {
        return [n integerValue];
    }else{
        return 37934;
    }
}


//退出账号
//一些全局操作
+ (void)quitLogin
{
    ShareData *shareData = [ShareData shareData];
    [shareData.firstView logOut];
    [shareData.secondView logOut];
    [shareData.thirdView logOut];
    [shareData.firstView.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
    [shareData.secondView.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
    [shareData.thirdView.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
     [shareData.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
   
    [shareData.scrollView setContentSize:CGSizeMake(DeviceWidth, DeviceHeight - kMyTabBarHeight)];
    shareData.sweetheartType = sweetheartType_NO;

    // 退订推送
    MLUser *user = [MLUser currentUser];
    AVInstallation *installation = [AVInstallation currentInstallation];
    NSArray *objects;
    if (user.type == MLUserType_NORMAL) {
        objects = @[user.objectId];
    }else if (user.gender==MLUserGender_MALE) {
        objects = @[user.objectId,@"SweetMale"];
    }else{
        objects = @[user.objectId,@"SweetFemale"];
    }
    [installation removeObjectsInArray:objects forKey:@"channels"];
    
    [installation saveInBackground];
    // 退出登录
    [MLUser logOut];
}



//检查是否展示提现功能
+ (BOOL)cheackConfigurationWithdraw
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"withdraw"]&&([[configuration objectForKey:@"withdraw"] isEqual: @1])) {
        return YES;
    }else{
        return NO;
    }
}

//检查是否使用筛选功能
+ (BOOL)cheackConfigurationScreen
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"screen"]&&([[configuration objectForKey:@"screen"] isEqual: @1])) {
        return NO;
    }else{
        return YES;
    }
}
////检查聊天是否收费
+ (BOOL)cheackConfigurationChatCharge
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"chatCharge"]&&([[configuration objectForKey:@"chatCharge"] isEqual: @1])) {
        //收费的
        return YES;
        
    }else{
        //不收费
        return NO;
    }
}
//是否显示充值的图片
+ (BOOL)cheackConfigurationChangeImage
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"changeImage"]&&([[configuration objectForKey:@"changeImage"] isEqual: @1])) {
        return YES;
    }else{
        return NO;
    }
}
//对筛选出的用户进行判断是否收费
+ (BOOL)judgeChatCharge
{
    //使用筛选功能并且是不收费的才确定是不收费的,
    if([self cheackConfigurationScreen]&&![self cheackConfigurationChatCharge]){
        return NO;
    }else{
        return YES;
    }
}
//是否显示情感热线
+ (BOOL)cheackConfigurationEmotionalHotline
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"emotionalHotline"]&&([[configuration objectForKey:@"emotionalHotline"] isEqual: @1])) {
        //
        return YES;
        
    }else{
        //
        return NO;
    }
}
//致新用户显示
+ (BOOL)cheackConfigurationUserHint
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"userHint"]&&([[configuration objectForKey:@"userHint"] isEqual: @1])) {
        //
        return YES;
        
    }else{
        //
        return NO;
    }
}
//礼物商场是否显示
+ (BOOL)cheackConfigurationGiftShop
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"giftShop"]&&([[configuration objectForKey:@"giftShop"] isEqual: @1])) {
        //
        return NO;
        
    }else{
        //
        return YES;
    }
}
//打卡是否显示
+ (BOOL)cheackConfigurationSignClock
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"signClock"]&&([[configuration objectForKey:@"signClock"] isEqual: @1])) {
        //
        return YES;
        
    }else{
        //
        return NO;
    }
}
//话题是否显示
+ (BOOL)cheackConfigurationTopic
{
    NSDictionary *configuration = [Utils plistName:@"configuration"];
    if (configuration&&[configuration objectForKey:@"topic"]&&([[configuration objectForKey:@"topic"] isEqual: @1])) {
        //
        return YES;
        
    }else{
        //
        return NO;
    }
}
//透传



+ (void)sendCmdMessageCMD:(NSString *)cmd ReceiverObjectId:(NSString *)objectId nickname:(NSString *)nickname
{
    EMChatCommand *cmdChat = [[EMChatCommand alloc] init];
    cmdChat.cmd = cmd;
    EMCommandMessageBody *body = [[EMCommandMessageBody alloc] initWithChatObject:cmdChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver: objectId bodies:@[body]];
    message.messageType = eMessageTypeChat;
    message.ext = [NSDictionary dictionaryWithObjectsAndKeys:nickname,@"nickname", nil];
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
}
+ (void)sendCmdMessageCMD:(NSString *)cmd ReceiverObjectId:(NSString *)objectId nickname:(NSString *)nickname orderId:(NSString *)orderId
{
    EMChatCommand *cmdChat = [[EMChatCommand alloc] init];
    cmdChat.cmd = cmd;
    EMCommandMessageBody *body = [[EMCommandMessageBody alloc] initWithChatObject:cmdChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver: objectId bodies:@[body]];
    message.messageType = eMessageTypeChat;
    message.ext = [NSDictionary dictionaryWithObjectsAndKeys:nickname,@"nickname",orderId,@"orderId", nil];
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
}


//number:需要处理的数字， position：保留小数点第几位，
+(double)roundUp:(double)number afterPoint:(int)position
{
    
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    
    NSDecimalNumber *ouncesDecimal;
    
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithDouble:number];
    
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [roundedOunces doubleValue];
    
}

//保存筛选记录
+(void)screenRecordSex:(NSInteger )sex userType:(NSInteger )userType;
{
    //三种状态
    NSString *plistName = [NSString stringWithFormat:@"%@screenRecord",@"123"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[NSNumber numberWithInteger:sex] forKey:@"sex"];
    [dic setValue:[NSNumber numberWithInteger:userType] forKey:@"userType"];
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
    
    
}
//获取筛选记录(有则从本地,没有,但是登录,就异性匹配,无登录,出现全部)
+(NSDictionary *)screenRecord
{
     NSString *plistName = [NSString stringWithFormat:@"%@screenRecord",@"123"];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}

//获取plist文件存储的字典
+ (NSDictionary *)plistName:(NSString *)plistName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [path firstObject];
    NSString *plistPath = [filePath stringByAppendingPathComponent:plistName];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    return dic;
}
//向plist文件中添加新的存储
+ (void)AddToPlistWithPlistName:(NSString *)plistName andDictionary:(NSDictionary *) dic
{
    NSFileManager *f = [NSFileManager defaultManager];
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [path firstObject];
    NSString *plistPath = [filePath stringByAppendingPathComponent:plistName];
    if (![f fileExistsAtPath:plistPath]) {
        [f createFileAtPath:plistPath contents:nil attributes:nil];
    }
    [dic writeToFile:plistPath atomically:YES];
}
//检查网络
+ (BOOL)inspectNetwork
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    
    if([r currentReachabilityStatus] == NotReachable){
        return NO;
    }else{
        return YES;
    }
}

//保存通过的通话申请
+(void)savePassChatApplyObjectID:(NSString *)objectID status:(NSInteger)status
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassChatApply",[MLUser currentUser].objectId];
    
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:[NSNumber numberWithInteger:status] forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
    //存储最新
}
//删除
+(void)removePassChatApplyObjectID:(NSString *)objectID
{
    NSDictionary *d = [Utils getPassChatApply];
    NSMutableDictionary *nd = [NSMutableDictionary dictionaryWithDictionary:d];
    [nd removeObjectForKey:objectID];
    NSString *plistName = [NSString stringWithFormat:@"%@PassChatApply",[MLUser currentUser].objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:nd];

}
//获取本地存储的通话申请(暂时一直获取)
+ (NSDictionary *)getPassChatApply
{
     NSString *plistName = [NSString stringWithFormat:@"%@PassChatApply",[MLUser currentUser].objectId];
     NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}


//保存对话题社的点赞记录
+(void)saveCircleObjectId:(NSString *)objectId
{
    NSString *plistName = [NSString stringWithFormat:@"%@praiseCircle",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//获取话题是的点赞记录
+ (NSDictionary *)getPraiseCircle
{
    NSString *plistName = [NSString stringWithFormat:@"%@praiseCircle",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//判断是否已经点过赞
+ (BOOL)isPraiseCircleObjectId:(NSString *)objectId
{
    //如果要是
    NSDictionary *friendDic = [Utils getPraiseCircle];
    if(friendDic&&[[friendDic objectForKey:objectId] isEqualToString:@"YES"]){
        return YES;
    }else{
        return NO;
    }
}
//保存好友字典
+(void)savePassFriendObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassFriend",[MLUser currentUser].objectId];
    
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//只保留这个
+(void)savePassFriendDictionary:(NSDictionary *)dic
{
      NSString *plistName = [NSString stringWithFormat:@"%@PassFriend",[MLUser currentUser].objectId];
     [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
}
//删除指定好友
+(void)removeObjectForFriendObjectID:(NSString *)objectID
{
    NSDictionary *d = [Utils getPassFriend];
    NSMutableDictionary *nd = [NSMutableDictionary dictionaryWithDictionary:d];
    [nd removeObjectForKey:objectID];
    [Utils savePassFriendDictionary:nd];
}
//获取本地存储的好友列表(暂时一直获取)
+ (NSDictionary *)getPassFriend
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassFriend",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//判断是不是好友
+(BOOL)isFriendObjectId:(NSString *)objectId
{
    //如果要是好友则不需要查询,不需要修改状态
    NSDictionary *friendDic = [Utils getPassFriend];
    if(friendDic&&[[friendDic objectForKey:objectId] isEqualToString:@"YES"]){
        return YES;
    }else{
        //不是好友
        return NO;
    }
}

//判断是不是恋人
+(BOOL)isSweetheartObjectId:(NSString *)objectId
{
    ShareData *sharedata = [ShareData shareData];
    MLUser *user = [MLUser currentUser];
    
    if (sharedata.firstView.sweetheart) {
        if ([sharedata.firstView.sweetheart.sponsor.objectId isEqualToString:objectId]&&[sharedata.firstView.sweetheart.winner.objectId isEqualToString:user.objectId]) {
            return YES;
        }
        if ([sharedata.firstView.sweetheart.winner.objectId isEqualToString:objectId]&&[sharedata.firstView.sweetheart.sponsor.objectId isEqualToString:user.objectId]) {
            return YES;
        }
        
        
    }
    if (sharedata.secondView.sweetheart) {
        if ([sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:objectId]&&[sharedata.secondView.sweetheart.winner.objectId isEqualToString:user.objectId]) {
            return YES;
        }
        if ([sharedata.secondView.sweetheart.winner.objectId isEqualToString:objectId]&&[sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:user.objectId]) {
            return YES;
        }
       
    }
    if (sharedata.thirdView.sweetheart) {
        if ([sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:objectId]&&[sharedata.secondView.sweetheart.winner.objectId isEqualToString:user.objectId]) {
            return YES;
        }
        if ([sharedata.secondView.sweetheart.winner.objectId isEqualToString:objectId]&&[sharedata.secondView.sweetheart.sponsor.objectId isEqualToString:user.objectId]) {
            return YES;
        }
    }
    return NO;
}


//保存喜欢的人的到字典
+(void)savePassLoveUserObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveUser",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//删除喜欢的人
+(void)removeObjectForLoveUserObjectID:(NSString *)objectID
{
    NSDictionary *d = [Utils getPassLoveUser];
    NSMutableDictionary *nd = [NSMutableDictionary dictionaryWithDictionary:d];
    [nd removeObjectForKey:objectID];
    [Utils savePassLoveuUserDictionary:nd];
}
//只保留这个字典(喜欢的人)
+ (void)savePassLoveuUserDictionary:(NSDictionary *)dic
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveUser",[MLUser currentUser].objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];

}
//获取本地存储的喜欢的人列表(暂时一直获取)
+ (NSDictionary *)getPassLoveUser
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveUser",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//判断是不是喜欢的人
+(BOOL)isLoveUserObjectId:(NSString *)objectId
{
    
    NSDictionary *friendDic = [Utils getPassLoveUser];
    if(friendDic&&[[friendDic objectForKey:objectId] isEqualToString:@"YES"]){
        return YES;
    }else{
        return NO;
    }
}


//保存喜欢的文章的到字典
+(void)savePassLoveArticleObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveArticle",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//删除喜欢的文章
+(void)removeObjectForLoveArticleObjectID:(NSString *)objectID
{
    NSDictionary *d = [Utils getPassLoveArticle];
    NSMutableDictionary *nd = [NSMutableDictionary dictionaryWithDictionary:d];
    [nd removeObjectForKey:objectID];
    [Utils savePassLoveuArticleDictionary:nd];
}
//只保留这个字典(喜欢的文章)
+ (void)savePassLoveuArticleDictionary:(NSDictionary *)dic
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveArticle",[MLUser currentUser].objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
}
//获取本地存储的喜欢的文章列表(暂时一直获取)
+ (NSDictionary *)getPassLoveArticle
{
    NSString *plistName = [NSString stringWithFormat:@"%@PassLoveArticle",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//判断是不是喜欢的文章
+(BOOL)isLoveArticleObjectId:(NSString *)objectId
{
    NSDictionary *friendDic = [Utils getPassLoveArticle];
    if(friendDic&&[[friendDic objectForKey:objectId] isEqualToString:@"YES"]){
        return YES;
    }else{
        return NO;
    }
}

//保存聊过天的人
+ (void)saveChatUserDictionary:(NSDictionary *)dic
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUser",[MLUser currentUser].objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:dic];
}
//获取聊过天的人的id字典
+ (NSDictionary *)getChatUserDic
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUser",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//保存聊过天的字典
+(void)saveChatUserObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUser",[MLUser currentUser].objectId];
    
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//保存聊过天的用户名字,头像
+(void)saveChatUserDataNicknameUser:(MLUser *)user
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUserNicknameHeadurl",[MLUser currentUser].objectId];
    
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    NSDictionary *userData = [NSDictionary dictionaryWithObjectsAndKeys:user.nickname,@"nickname",(!user.subAvatar || [user.subAvatar isEqualToString:@""])?user.avatar.url:user.subAvatar,@"headurl", nil];
    [ndic setObject:userData forKey:user.objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//获取聊过天的用户名字,头像
+ (NSDictionary *)getChatUserNicknameHeadurlDic
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUserNicknameHeadurl",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//根据用户id获取单个用户的信息
+ (NSDictionary *)getUserNicknameHeadurlObjectId:(NSString *)objectId;
{
    NSDictionary *dic = [Utils getChatUserNicknameHeadurlDic];
    return [dic objectForKey:objectId];
}

//更改资料后发送给所有需要发送的人(聊过天的和好友)
+ (void)changeUserDataSendUsers
{
    NSDictionary *friendDic = [Utils getPassFriend];
    NSDictionary *chatDic = [Utils getChatUserDic];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:friendDic];
    [dic addEntriesFromDictionary:chatDic];
    [dic removeObjectForKey:@"new_friend"];
    [dic removeObjectForKey:@"new_sweet"];
    [dic removeObjectForKey:@"mlsystem"];
    NSArray *arr = [dic allKeys];
    if(arr&&arr.count){
        NSDictionary *params = @{@"touserIds": arr, @"fromuserId": [MLUser currentUser].objectId};
        [AVCloud callFunctionInBackground:@"sendUpdateMsg" withParameters:params block:^(id object, NSError *error) {
            if (!error) {
                //发送成功
            }
        }];
    }
}
//保存试聊订单对方objectID
+ (void)saveTestOrderObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@TestOrder",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
    
}
//判断是否和他试聊过
+ (BOOL)isTestOrderObjectID:(NSString *)objectID
{
    
    NSString *plistName = [NSString stringWithFormat:@"%@TestOrder",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    if(dic&&[[dic objectForKey:objectID] isEqualToString:@"YES"]){
        return YES;
    }else{
        return NO;
    }
}
////删除试聊记录
//+ (void)removeTestOrderObjectID:(NSString *)objectID
//{
//    NSString *plistName = [NSString stringWithFormat:@"%@TestOrder",[MLUser currentUser].objectId];
//    NSDictionary *dic = [Utils plistName:plistName];
//    NSMutableDictionary *nDic = [NSMutableDictionary dictionaryWithDictionary:dic];
//    [nDic removeAllObjects];
//    [Utils AddToPlistWithPlistName:plistName andDictionary:nDic];
//    
//}
////保存聊天订单对方objectID
//+ (void)saveOrderObjectID:(NSString *)objectID
//{
//    NSString *plistName = [NSString stringWithFormat:@"%@Order",[MLUser currentUser].objectId];
//    NSDictionary *dic = [Utils plistName:plistName];
//    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
//    [ndic setObject:@"YES" forKey:objectID];
//    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
//}
////判断是否和他聊过天
//+ (BOOL)isOrderObjectID:(NSString *)objectID
//{
//    NSString *plistName = [NSString stringWithFormat:@"%@Order",[MLUser currentUser].objectId];
//    NSDictionary *dic = [Utils plistName:plistName];
//    if(dic&&[[dic objectForKey:objectID] isEqualToString:@"YES"]){
//        return YES;
//    }else{
//        return NO;
//    }
//}
//检查文章是否已经阅读
+(BOOL)inspectArticleReadObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@ArticleRead",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSString *str = [dic objectForKey:objectID];
    if (str&&[str isEqualToString:@"YES"]) {
        return YES;
    }else{
        return NO;
    }
    
}
//保存已经阅读的文章
+(void)saveArticleReadObjectID:(NSString *)objectID
{
    NSString *plistName = [NSString stringWithFormat:@"%@ArticleRead",[MLUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [ndic setObject:@"YES" forKey:objectID];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}




+(void)alert:(NSString*)msg{
    UIAlertView *alertView=[[UIAlertView alloc]
                             initWithTitle:nil message:msg delegate:nil
                             cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
}

+(void)alertError:(NSError*)error{
    [Utils alert:@"网络异常"];
}

+(NSString*)md5OfString:(NSString*)s{
    const char *ptr = [s UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(ptr, (int)strlen(ptr), md5Buffer);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];
    
    return output;
}

+(NSMutableArray*)setToArray:(NSMutableSet*)set{
    return [[NSMutableArray alloc] initWithArray:[set allObjects]];
}

+(void)filterError:(NSError*)error callback:(CDBlock)callback{
    if(error){
        [Utils alertError:error];
    }else{
        callback();
    }
}

+(NSString*)generateRandomNumString:(int)num {
    NSMutableString* string = [NSMutableString stringWithCapacity:num];
    for (int i = 0; i < num; i++) {
        [string appendFormat:@"%d", arc4random() % 10];
    }
    return string;
}


+(NSString *)generateOrderCode {
    // 计算订单编号
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *codeStr = [NSString stringWithFormat:@"%@%@", dateStr, [self generateRandomNumString:8]];
    return codeStr;
}


+(UIView*)HUDImage :(UIImage*)image Title:(NSString*)title Content:(NSString*)content Timer:(NSTimeInterval)timer{

    UIView*bgView=[[UIView alloc]initWithFrame:[UIApplication sharedApplication].delegate.window.bounds];
//    [bgView setBarStyle:UIBarStyleBlack];
//    bgView.alpha = 0;
//    bgView.userInteractionEnabled = NO;
    bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    [[UIApplication sharedApplication].delegate.window addSubview:bgView];
    
    [self Hidden:bgView Bool:YES];
    
    
    UIToolbar*View_screen=[[UIToolbar alloc]init];
    [View_screen setBarStyle:UIBarStyleDefault];
//    View_screen.backgroundColor=[UIColor whiteColor];
    View_screen.layer.masksToBounds = YES;//开启圆角
    [View_screen.layer setCornerRadius:10];
    [bgView addSubview:View_screen];

    if (image==nil) {
        View_screen.frame=CGRectMake(20, (DeviceHeight-100)/2, DeviceWidth-40, 100);
    }else{
        View_screen.frame=CGRectMake(20, (DeviceHeight-200)/2, DeviceWidth-40, 200);
    }
    
    UIImageView*Imageview_screen=[[UIImageView alloc]initWithFrame:CGRectMake(((DeviceWidth-40)-100)/2, 20, 100, 100)];
    Imageview_screen.image=image;
    [View_screen addSubview:Imageview_screen];
    
    UILabel*Label_screen=[[UILabel alloc]initWithFrame:CGRectMake(0, View_screen.bounds.size.height-70, DeviceWidth-40, 20)];
    Label_screen.font=[UIFont fontWithName:FontName size:17];
    Label_screen.textColor=[UIColor blackColor];
    Label_screen.text=title;
    Label_screen.adjustsFontSizeToFitWidth = YES;
    Label_screen.textAlignment=NSTextAlignmentCenter;
    [View_screen addSubview:Label_screen];
    
    if (content==nil) {
        Label_screen.frame=CGRectMake(0, View_screen.bounds.size.height-60, DeviceWidth-40, 20);
    }else{
        Label_screen.frame=CGRectMake(0, View_screen.bounds.size.height-70, DeviceWidth-40, 20);
    }
    
    UILabel*Label_screen2=[[UILabel alloc]initWithFrame:CGRectMake(10, View_screen.bounds.size.height-45, DeviceWidth-60, 30)];
    Label_screen2.font=[UIFont fontWithName:FontName size:15];
    Label_screen2.textColor=[UIColor grayColor];
    Label_screen2.text=content;
    Label_screen2.numberOfLines=0;
    Label_screen2.textAlignment=NSTextAlignmentCenter;
    [View_screen addSubview:Label_screen2];
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timer * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.55
                         animations:^{
                             bgView.alpha = 0;
                             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.55 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                 [bgView removeFromSuperview];
                             });
                         }];
    });

    return bgView;

}

+(UIView*)Hidden :(UIView*)View Bool:(BOOL)bool2{
    if (bool2==YES) {
        View.alpha = 0;
    }else{
        View.alpha = 1;
    }
    [UIView animateWithDuration:0.25
                     animations:^{
                         if (bool2==YES) {
                             View.alpha = 1;
                         }else{
                             View.alpha = 0;
                         }
                     }];
    return View;
}



+ (void)saveToDefaults:(id)obj forKey:(NSString*)key
{
    if ([obj isKindOfClass:[NSNull class]]) {
        obj=@"";
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:obj forKey:key];
    [defaults synchronize];
    
}

+ (id)defaultsForKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}

+ (void)Theskin:(int)count Vc:(UIViewController*)vc
{
    NSArray*colorArr=@[UIColorFromRGB(0xFE6A66),[UIColor paperColorAmber], [UIColor paperColorDeepPurple800],[UIColor paperColorGreen400],[UIColor paperColorRed900],[UIColor paperColorLightBlue500],[UIColor paperColorLightGreen600],[UIColor paperColorBrown600],[UIColor paperColorOrange900],[UIColor paperColorPurple800],[UIColor paperColorTeal500],[UIColor paperColorPinkA400],[UIColor paperColorTeal200],[UIColor paperColorRed600],[UIColor paperColorPurple600]];
    
    UIColor*color= [colorArr[count] colorWithAlphaComponent:0.99];
    [Utils saveArchiveData:color DIR:APP_THEME_NAV_COLOR forKey:@"Theskin.colo"];
    
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
    [vc.navigationController.navigationBar
     setBackgroundImage:[UIImage imageWithColor:color]
     forBarMetrics:UIBarMetricsDefault];
    
}

+ (void)saveArchiveData:(id)data DIR:(NSString*)dir forKey:(NSString*)key
{
    NSString *Path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:dir];
    NSString *filename = [Path stringByAppendingPathComponent:key];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:filename isDirectory:&isDir];
    if(!(isDirExist && isDir))
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:Path withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建文件夹失败！");
            [HUD Prompt:@"操作失败!"];
        }
    }
    
    [NSKeyedArchiver archiveRootObject:data toFile:filename];
}

+ (id)readArchiveData:(NSString*)dir ForKey:(NSString*)key{
    NSString *docPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:dir];
    NSString *path = [docPath stringByAppendingPathComponent:key];
    NSFileManager *fm = [NSFileManager defaultManager];
    id data;
    if ([fm fileExistsAtPath:path]) //如果文件中有,就从文件中取出来,从文件中读取
    {
        data=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
        
    }else{
        return nil;
    }
    return data;
    
}

+(BOOL)removeItemDIR:(NSString*)dir ForKey:(NSString*)key
{
    NSString *docPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:dir];
    NSString *path = [docPath stringByAppendingPathComponent:key];
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:path]) {
        [defaultManager removeItemAtPath:path error:nil];
        return YES;
    }else{
        return NO;
    }
    
}
+ (void)animationMobileTimer:(CGFloat )timer View:(UIView*)view Rect:(CGRect)rect{
    [UIView beginAnimations:@"moveAnimation" context:@"move"];//设置动画名称和参数信息.可以用来传值;
    [UIView setAnimationDuration:timer];//设置动画时长
    [UIView setAnimationDelegate:self];//设置动画代理
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];//设置动画缓进缓出
    view.frame=rect;//结束时的坐标;
    [UIView commitAnimations];//提交动画 动画的开始.
}

+ (void)animationSpringBounciness:(CGFloat )bounciness View:(UIView*)view Rect:(CGRect)rect{
    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    positionAnimation.toValue = [NSValue valueWithCGRect:rect];
    positionAnimation.springBounciness = bounciness;
    [view.layer pop_addAnimation:positionAnimation forKey:@"animationSpringBounciness"];
}

+ (void)popBasicAnimationPropertyName:(NSString*)aName toValue:(id)aValue View:(UIView *)view {
    POPBasicAnimation *layerScaleAnimation = [POPBasicAnimation animationWithPropertyNamed:aName];
    layerScaleAnimation.toValue = aValue;
    [view.layer pop_addAnimation:layerScaleAnimation forKey:@"animationMobileTimer"];
}


+ (void)popSpringAnimationPropertyName:(NSString*)aName toValue:(id)aValue View:(UIView *)view {
    POPSpringAnimation *layerScaleAnimation = [POPSpringAnimation animationWithPropertyNamed:aName];
    layerScaleAnimation.toValue = aValue;
    [view.layer pop_addAnimation:layerScaleAnimation forKey:@"animationMobileTimer"];
}


+ (BOOL)onePerform:(NSString*)str
{
    BOOL wasShown = [[NSUserDefaults standardUserDefaults] boolForKey:str];
    if (wasShown) {
        return NO;
    } else {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:str];
        return YES;
    }
}

+(CGSize)LabeSizeText:(NSString*)text Font:(UIFont*)font
{
    CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    return size;
}

+(CGSize)LabeSizeLabelheight:(NSString*)text Font:(UIFont*)font
{
    
    //    CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    //    NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:font,NSFontAttributeName,nil];
    //    CGSize size = [text sizeWithAttributes:dic];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];    ////////   ios 7
    CGSize size = [text boundingRectWithSize:CGSizeMake(DeviceWidth-120, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return size;
}



-(void)viewControllerPrompt:(CGRect)rect Text:(NSString*)text Image:(UIImage*)image{
    
    UIView *promptView = [[UIView alloc]initWithFrame:rect];
    promptView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    UILabel *promptText = [[UILabel alloc]initWithFrame:CGRectMake(70, (rect.size.height-50)/2, rect.size.width-140, 50)];
    promptText.text = text;
    promptText.numberOfLines = 0;
    promptText.textAlignment = NSTextAlignmentCenter;
    promptText.font=[UIFont fontWithName:FontName size:15];
    promptText.textColor = [UIColor grayColor];
    [promptView addSubview:promptText];
    
    CGFloat imageWidth = DeviceWidth-200;
    
    if (image) {
        UIImageView *promptImage = [[UIImageView alloc]initWithFrame:CGRectMake((rect.size.width-imageWidth)/2, ((rect.size.height)/2)-(imageWidth), imageWidth, imageWidth)];
        [promptImage setContentMode:UIViewContentModeScaleAspectFit];
        promptImage.clipsToBounds = YES;
        promptImage.image = image;
        [promptView addSubview:promptImage];
    }else{
        UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        testActivityIndicator.center = CGPointMake(rect.size.width/2,  (rect.size.height-80)/2);//只能设置中心，不能设置大小
        testActivityIndicator.color = [UIColor blackColor]; // 改变圈圈的颜色为红色； iOS5引入
        [testActivityIndicator startAnimating]; // 开始旋转
//        [testActivityIndicator stopAnimating]; // 结束旋转
//        [testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏
        [promptView addSubview:testActivityIndicator];

    }
    self.viewPrompt = promptView;
}

-(void)viewControllerPromptstopAnimating{
    [self.viewPrompt removeFromSuperview]; // 结束旋转
}

+(void)pushTabbarHidden:(UIViewController*)viewController Selfvc:(UIViewController*)selfvc
{
    viewController.hidesBottomBarWhenPushed = YES;
    [selfvc.navigationController pushViewController:viewController animated:YES];
}

+(void)playWavName:(NSString*)wavName
{
    NSString *path = [[NSBundle mainBundle] pathForResource:wavName ofType:@"wav"];
    if (path) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]),&shake_sound_male_id);
        AudioServicesPlaySystemSound(shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
}

+(void)loginVC:(UIViewController*)vc
{
    // 如果未登录跳转到登录页面,默认跳转到主页面
    MLUser *currentUser = [MLUser currentUser];
    [currentUser refreshInBackgroundWithBlock:nil];
    if (!currentUser && currentUser.isUserInited) {
        
    }else{
        // 如果用户已填写了初始化信息
        UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
        Login.modalPresentationStyle = UIModalPresentationFormSheet;
        [vc presentViewController:Login animated:YES completion:nil];
        return;
    }
}

+(BOOL)userinit:(UIViewController*)vc
{
    if (![MLUser currentUser].isUserInited) {
        [HUD Prompt:@"请先登录"];
        UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
        Login.modalPresentationStyle = UIModalPresentationFormSheet;
        [vc presentViewController:Login animated:YES completion:nil];
        return NO;
    }
    return YES;
}

@end
